%% @author Administrator
%% @doc @todo Add description to account.


-module(account_api).

-include("account.hrl").
-include("global.hrl").
-include("global_data.hrl").
-include("proto.hrl").
-include("pb_account.hrl").

%% ====================================================================
%% API functions
%% ====================================================================
-export([]).

-export([login/2
		]).

%% ====================================================================
%% Internal functions
%% ====================================================================




login(?undefined, Player) ->
	Player;
login(AccountName, Player) ->
	{Uid, Roles} = get_account_uid_roles(AccountName),
	add_login_log(Uid, AccountName),
	PRoles = [#p_roles{uuid = UUid, rid = Rid, level = Level, name = Name, index = Index}||
			  #role{uuid = UUid, rid = Rid, level = Level, role_name = Name, index = Index}<-Roles],
	Msg = #s2c_pb_10000{uid = Uid, p_roles = PRoles},
	user_svr_util:send_msg(?PROTO_MSG_LOGIN, Msg),
	{noreply, Player}.

%% @doc 获取当前最大uid - 以当前服务器id*10000作为当前服第一个uid
get_max_uid() ->
	global_svr_util:get_global_data(?GLOBAL_DATE_KEY_MAX_UID, util:get_server_id()*10000).

%% @doc 当前最大uid自增1
incr_max_uid() ->
	CurMaxId = global_svr_util:get_global_data(?GLOBAL_DATE_KEY_MAX_UID, 0),
	global_svr_util:set_global_data(?GLOBAL_DATE_KEY_MAX_UID, CurMaxId + 1).


%% @doc 新增登录记录
add_login_log(Uid, AccountName) ->
	NowTime = util_time:get_now_time(),
	case ets:lookup(?ETS_ACCOUNT_NAME, AccountName) of
		[{AccountName, Uid, _Roles}|_] ->
			?pass;
		_ ->
			ets:insert(?ETS_ACCOUNT_NAME, {AccountName, Uid, []})
	end,
	ets:insert(?ETS_ONLINE_UID, {Uid, NowTime}),
	ets:insert(?ETS_UID_PID, {Uid, self()}).

%% @doc 通过账号获取uid和角色列表
get_account_uid_roles(AccountName) ->
	case ets:lookup(?ETS_ACCOUNT_NAME, AccountName) of
		[{AccountName, Uid, Roles}|_] ->  %% 存在则用现有的
			{Uid, Roles};
		_ ->  %% 不存在则从最大值中取
			Uid = get_max_uid(),
			incr_max_uid(),
			{Uid, []}
	end.




